<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';

import { CloseBold } from '@element-plus/icons-vue';
import { ElButton, ElOption, ElSelect, ElTag } from 'element-plus';

import { addObj as addSpecsObj } from '#/api/product/goods-specs';
import {
  addObj as addSpecsValueObj,
  getList as getSpecsValueList,
} from '#/api/product/goods-specs-value';
import SelectMaterial from '#/components/select-material/index.vue';

import SkuTable from './sku-table/index.vue';

const props = defineProps({
  specsListProp: {
    type: Object,
    default: () => {},
  },
  skusData: {
    type: Array,
    default: () => [],
  },
  goodsSpuSpecs: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['getGoodsSkus']);

const state = reactive({
  specsValueId: null,
  specsValueList: [{ id: '', name: '', disabled: false }],
  visible: true,
});
const skuTableRef = ref();
const spuSpecs = ref<any>(props.goodsSpuSpecs);
const specsList = ref<any>(props.specsListProp);
const getGoodsSkus = (skus: any) => {
  emit('getGoodsSkus', skus, spuSpecs.value);
};
watch(
  () => props.goodsSpuSpecs,
  (val) => {
    spuSpecs.value = val;
  },
  { deep: true, immediate: true },
);
// 监听goodsSpuSpecs
watch(
  () => props.goodsSpuSpecs,
  (val) => {
    spuSpecs.value = val;
  },
  { deep: true, immediate: true },
);
// 监听specsListProp
watch(
  () => props.specsListProp,
  (val) => {
    specsList.value = val;
    //
  },
  { deep: true },
);

/**
 * 添加规格
 */
const addSpecs = () => {
  specsList.value.forEach((item: any) => {
    spuSpecs.value.forEach((item2: any) => {
      item.disabled = item.id === item2.specsId;
    });
  });
  spuSpecs.value.push({
    specsId: '',
    specsName: '',
    goodsSkuSpecsValues: [],
  });
};
/**
 * 添加规格值
 */
const addSpecsValue = (specsId: string, index: number) => {
  state.specsValueList = [];
  // 查询规格值
  getSpecsValueList({ specsId }).then((response) => {
    state.specsValueList = response;
    state.specsValueList.forEach((item: any) => {
      spuSpecs.value[index].goodsSkuSpecsValues.forEach((valueItem: any) => {
        if (valueItem.specsValueId === item.id) {
          item.disabled = true;
        }
      });
    });
  });
};
/**
 * 选择规格事件
 */
const changeSpecs = async (row: any, index: number) => {
  const targetSpec = spuSpecs.value[index];
  if (!targetSpec || !row?.specsId) return;

  const existingSpec = specsList.value.find(
    (item: any) => item.id === row.specsId,
  );

  if (existingSpec) {
    targetSpec.specsName = existingSpec.name;
  } else {
    try {
      const specsObj = await addSpecsObj({ name: row.specsId });
      specsList.value.push(specsObj);
      targetSpec.specsName = specsObj.name;
      targetSpec.specsId = specsObj.id;
    } catch (error) {
      console.error('添加规格失败:', error);
    }
  }

  // 清空规格值
  targetSpec.goodsSkuSpecsValues = [];
};
/**
 * 选择规格值事件
 */
const changeSpecsValue = async (specsValueId: null | string, index: number) => {
  if (!specsValueId || !spuSpecs.value[index]) return;

  const targetSpec = spuSpecs.value[index];

  const existingValue = state.specsValueList.find(
    (item: any) => item.id === specsValueId,
  );

  if (existingValue) {
    existingValue.disabled = true;
    targetSpec.goodsSkuSpecsValues.push({
      specsValueId: existingValue.id,
      specsValueName: existingValue.name,
      picUrl: '',
    });
  } else {
    try {
      const specsObj = await addSpecsValueObj({
        name: specsValueId,
        specsId: targetSpec.specsId,
      });
      targetSpec.goodsSkuSpecsValues.push({
        specsValueId: specsObj.id,
        specsValueName: specsObj.name,
        picUrl: '',
      });
    } catch (error) {
      console.error('添加规格值失败:', error);
    }
  }

  state.specsValueId = null;
};
/**
 * 删除规格
 */
const delSpecs = (row: any, index: number) => {
  specsList.value.forEach((item: any) => {
    if (item.id === row.specsId) {
      item.disabled = false;
    }
  });
  spuSpecs.value.splice(index, 1);
};
/**
 * 删除规格值
 */
const delSpecsValue = (index: number, specsIndex: number) => {
  spuSpecs.value[specsIndex].goodsSkuSpecsValues.splice(index, 1);
};
const visibleChange = (val: any) => {
  if (val) {
    specsList.value.forEach((item: any) => {
      item.disabled = false;
      spuSpecs.value.forEach((item2: any) => {
        if (item.id === item2.specsId) {
          item.disabled = true;
        }
      });
    });
  }
};
</script>
<template>
  <div>
    <div class="specs-border">
      <div v-if="spuSpecs && spuSpecs.length > 0">
        <div v-for="(item, index) in spuSpecs" :key="index">
          <div class="goods-specs-item">
            规格名：
            <ElSelect
              v-model="item.specsId"
              filterable
              allow-create
              placeholder="请输入规格名"
              @visible-change="visibleChange(item)"
              @change="changeSpecs(item, index)"
              style="width: 200px"
            >
              <ElOption
                v-for="spec in specsList"
                :key="spec.id"
                :label="spec.name"
                :value="spec.id"
                :disabled="spec.disabled"
              />
            </ElSelect>
            <div style="float: right">
              <ElButton
                circle
                @click="delSpecs(item, index)"
                :icon="CloseBold"
              />
            </div>
          </div>

          <div class="specs-value-list">
            规格值：
            <div
              v-for="(itemValue, indexValue) in item.goodsSkuSpecsValues"
              :key="indexValue"
            >
              <ElTag
                style="margin: 10px"
                effect="plain"
                closable
                @close="delSpecsValue(indexValue, index)"
              >
                {{ itemValue.specsValueName }}
              </ElTag>
              <SelectMaterial
                class="specs-image"
                v-if="index === 0"
                v-model="itemValue.picUrl"
                :can-choose-images-num="1"
              />
            </div>
            <ElSelect
              v-model="state.specsValueId"
              filterable
              allow-create
              placeholder="请输入规格值"
              style="width: 200px"
              @focus="addSpecsValue(item.specsId, index)"
              @change="changeSpecsValue(state.specsValueId, index)"
            >
              <ElOption
                v-for="specsValueOption in state.specsValueList"
                :key="specsValueOption.id"
                :label="specsValueOption.name"
                :value="specsValueOption.id"
                :disabled="specsValueOption.disabled"
              />
            </ElSelect>
          </div>
        </div>
      </div>
      <ElButton @click="addSpecs" v-if="spuSpecs.length < 3">
        添加规格
      </ElButton>
    </div>
    <div style="margin-top: 20px">
      <SkuTable
        ref="skuTableRef"
        :skus-data="skusData"
        :goods-spu-specs="spuSpecs"
        @get-goods-skus="getGoodsSkus"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.specs-border {
  padding: 20px;
  border: 1px solid #f2f2f2;
}

.specs-value-select {
  width: 100px;
  padding: 10px;
}

.specs-value-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 20px;
  color: var(--el-text-color-regular);
}

.goods-specs-item {
  padding: 20px;
  color: var(--el-text-color-regular);
  background-color: hsl(var(--card));
}

.specs-image {
  display: flex;
  justify-content: center;
  margin-right: 0;
}
</style>
